import { ref, computed, watch, onMounted } from "vue";

export default {
  name: "AnimatedNumber",
  template: `<div class="number-container">
    <span :style="numberStyle">{{ formattedNumber }}</span>
  </div>`,
  props: {
    value: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    const currentNumber = ref(props.value);
    const targetNumber = ref(props.value);

    const formattedNumber = computed(() => {
      return currentNumber.value.toFixed(2); // 保留两位小数，根据需要调整
    });

    const numberStyle = computed(() => {
      return {
        transition: "opacity 1s, transform 1s",
        opacity: 1,
        transform: `scale(1)`
      };
    });

    const updateNumber = () => {
      const start = currentNumber.value;
      const end = targetNumber.value;
      let step = (end - start) / 100; // 100步完成过渡

      const animate = () => {
        if (
          (end > start && currentNumber.value < end) ||
          (end < start && currentNumber.value > end)
        ) {
          currentNumber.value += step;
          requestAnimationFrame(animate);
        }
      };

      animate();
    };

    watch(
      () => props.value,
      newValue => {
        targetNumber.value = newValue;
        // 重置数字以触发重新渲染和动画
        currentNumber.value = Number(formattedNumber.value.replace(".", ""));
        // 强制样式刷新
        setTimeout(() => {
          numberStyle.value.opacity = 0;
          requestAnimationFrame(() => {
            numberStyle.value.opacity = 1;
            numberStyle.value.transform = `scale(1.1) scale(1)`; // 轻微缩放效果
            updateNumber();
          });
        }, 0);
      },
      { immediate: true }
    );

    return {
      formattedNumber,
      numberStyle
    };
  }
};
